package example.androiddemo.common;

import android.app.Activity;
import android.app.Application;
import android.os.Process;

import java.lang.ref.WeakReference;
import java.util.Stack;

/**
 * Created by asus on 2016/9/20.
 */
public class AppManager {
    public AppManager() {
    }

    static AppManager instance = new AppManager();

    public static AppManager getInstance() {
        return instance;
    }

    Application app;

    public void init(Application app) {
        this.app = app;
    }

    //使用弱引用降低内存泄漏的风险
    Stack<WeakReference<Activity>> activityStack = new Stack<>();

    //退出App
    private void quitApp() {
        finishAllAct();
        Process.killProcess(Process.myPid());
    }

    private void finishAllAct() {
        //在遍历的时候 去修改集合元素 可能会出现问题  所以 我们可以倒序循环
        for (int i = activityStack.size() - 1; i > 0; i--) {
            Activity activity = activityStack.get(i).get();
            if (activity != null) {
                activity.finish();
            }
        }
    }

    public void addAct(Activity activity) {
        activityStack.add(new WeakReference<Activity>(activity));
    }

    public void removeAct(Activity activity) {
        for (int i = 0; i < activityStack.size(); i++) {
            if (activityStack.get(i).get() == activity) {
                activityStack.remove(i);
                break;
            }
        }

    }

    /**
     * 我们需要写一个方法 能够拿到栈顶的activity  以方便我们在弹出异常提示框的时候拿到对应的上下文对象
     */
    public Activity getTopAct() {
        if (activityStack.size() > 0) {
            return activityStack.peek().get();
        } else {
            return null;
        }
    }
}
